#define LCD_RS  P1_2
#define LCD_R_W P1_3
#define LCD_E   P1_4

#include "timer.h"
#include "configuration.h"

/**********************************************************/ 
void lcdCommand(char i) 
{
    P2 = i; //put data on output Port 
    LCD_RS =0; //D/I=LOW : send instruction 
    LCD_R_W =0; //R/W=LOW : Write 
    LCD_E = 1;
    delaySmall(); //enable pulse width >= 300ns 
    LCD_E = 0; //Clock enable: falling edge 
    delaySmall();
} 
/**********************************************************/ 
void lcdWrite(char i) 
{ 
    P2 = i; //put data on output Port 
    LCD_RS =1; //D/I=LOW : send data 
    LCD_R_W =0; //R/W=LOW : Write 
    LCD_E = 1;
    delaySmall(); //enable pulse width >= 300ns 
    LCD_E = 0; //Clock enable: falling edge
    delaySmall();
} 
/**********************************************************/ 
void InitLCD() 
{ 
    P2M1=0;
    P2M2=0;

    P1M1 &= ~(P1M1_2 | P1M1_3 | P1M1_4);
    P1M2 &= ~(P1M1_2 | P1M1_3 | P1M1_4);

    LCD_E = 0; 
    delay(100); //Wait >15 msec after power is applied 
    lcdCommand(0x30); //lcdCommand 0x30 = Wake up 
    delay(5); //must wait 5ms, busy flag not available 
    lcdCommand(0x30); //lcdCommand 0x30 = Wake up #2 
    delay(1); //must wait 160us, busy flag not available 
    lcdCommand(0x30); //lcdCommand 0x30 = Wake up #3 
    delay(1); //must wait 160us, busy flag not available 
    lcdCommand(0x38); //Function set: 8-bit/2-line 
    lcdCommand(0x10); //Set cursor 
    lcdCommand(0x0c); //Display ON; Cursor ON 
    lcdCommand(0x06); //Entry mode set
    
    lcdCommand(LCD_CLEAR);
} 
/**********************************************************/

void lcdClear()
{
    lcdCommand(LCD_CLEAR);
}

void setLcdCursor(int row, int col)
{
    lcdCommand(LCD_CURSOR | (col + row*40));
}

void setLcdHome()
{
    setLcdCursor(0,0);
}

void writeString(char* c)
{
    while (*c)
        lcdWrite(*c++);
}

void writeNum(unsigned long num) // the compiler does not like sprintf() T.T
{
    char numDigits = 1;
    unsigned long tempNum = num;
    static char str[14];
    while (tempNum /= 10)
        ++numDigits;

    str[numDigits--] = '\0';
    for (; numDigits >= 0; --numDigits)
    {
        str[numDigits] = (char)(num % 10 + 48); // ascii conversion
        num /= 10;
    }
    writeString(str);
}